from PIL import Image, ImageFont, ImageDraw, ImageFilter

import string, random, os


# 方法 获得四位随机数字
def getRandomChar():
    return [random.choice(string.ascii_letters) for _ in range(4)]


# 方法 获取随机颜色
def getRandomColor():
    return (random.randint(30, 100), random.randint(30, 100), random.randint(30, 100))


# 主方法 获取验证码图片
def getCodePicture(outPath):
    # 图片宽高
    width = 240
    height = 60
    # 创建空白画布
    image = Image.new('RGB', (width, height), (180, 180, 180))
    # 验证码字体
    font = ImageFont.truetype('simsun.ttf', 40)
    # 画出画布，获取画布对象
    draw = ImageDraw.Draw(image)
    # 创建验证码对象
    code = getRandomChar()
    # 吧验证码写到画布上
    for x in range(4):
        draw.text((60 * x + 10, 0), code[x], font=font, fill=getRandomColor())
    # 填充噪点
    for _ in range(random.randint(1500, 3000)):
        draw.point((random.randint(0, width), random.randint(0, height)), fill=getRandomColor())
    # 模糊处理
    image = image.filter(ImageFilter.BLUR)
    # 保存
    image.save(outPath + '\\' + "".join(code) + ".join", 'jpeg')


if __name__ == '__main__':
    """
    测试20240425
    225199992
    2250
    """
    getCodePicture(os.getcwd())
